<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Utils {
	static function genUniqName($name, $path) {
		$ext = '.' . pathinfo($name, PATHINFO_EXTENSION);
		$md5name = md5(rand());
		$newfile = trim(' /\\', $path) . DIRECTORY_SEPARATOR . $md5name . $ext;
		if (file_exists($newfile)) {
			return self::genUniqName($name, $path);
		}
		return $md5name . $ext;
	}

	static function toProportionalSize($file, $size, $unlink = true) {
		$im = imagecreatefromstring(file_get_contents($file));
		$width =  imagesx($im);
		$height = imagesy($im);
		$kwidth =  $width / $size;
		$kheight = $height / $size;
		$k = ($kwidth > $kheight) ? $kwidth : $kheight;
		$nwidth = $width / $k;
		$nheight = $height / $k;
		$nim = imagecreate($nwidth, $nheight);
		$filepart = pathinfo($file);
		$ext = image_type_to_extension(IMAGETYPE_PNG, true);
		if ($unlink) unlink($file);
		if (imagecopyresized($nim, $im, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
			imagepng($nim, $filepart['dirname'] . DIRECTORY_SEPARATOR . $filepart['filename'] . $ext);
		}
		imagedestroy($im);
		imagedestroy($nim);
		return $filepart['filename'] . $ext;
	}
}
